package main

import (
	"fmt"
	"math"
	"strconv"
	"strings"
)

func main() {
	fmt.Println(fractionAddition("1/3-2/3+1/2"))
}

func fractionAddition(expression string) string {
	m := 0 //结果分子
	n := 1 //结果分母
	cur := ""
	for i, ch := range []rune(expression) {
		if ch == '+' || ch == '-' {
			if i == 0 {
				cur = cur + string(ch)
			} else {
				//计算
				//fmt.Println("1", cur)
				sp := strings.Split(cur, "/")
				m1, _ := strconv.Atoi(sp[0])
				n1, _ := strconv.Atoi(sp[1])
				m, n = add(m, n, m1, n1)
				//重新记录下一个分数
				cur = string(ch)
			}
		} else {
			cur = cur + string(ch)
		}
	}
	//计算
	//fmt.Println( "2 ",cur)
	sp := strings.Split(cur, "/")
	m1, _ := strconv.Atoi(sp[0])
	n1, _ := strconv.Atoi(sp[1])
	m, n = add(m, n, m1, n1)
	return strconv.Itoa(m) + "/" + strconv.Itoa(n)
}

/*
计算m1/n1 + m2/n2 = m/n
*/
func add(m1, n1 int, m2, n2 int) (m, n int) {
	m = m1*n2 + m2*n1
	n = n1 * n2
	//化为最简
	g := gcd(int(math.Abs(float64(m))), n)
	return m / g, n / g
}

/*
求最大公约数
*/
func gcd(num1, num2 int) int {
	temp := num1 % num2
	for temp != 0 {
		num1 = num2
		num2 = temp
		temp = num1 % num2
	}
	return num2
}
